#include "multicast.h"
#include <stdio.h>
#include "socket.h"
#include "wizchip_conf.h"

/* IPv4 mode multicast looptest */
int32_t multicast_loopback(uint8_t sn, uint8_t* buf, uint8_t* multicast_mac, uint8_t* multicast_ip, uint16_t multicast_port, uint8_t loopback_mode)
{
    uint8_t status;
    static uint8_t dest_ip[16] = {0,};
    static uint16_t dest_port;
    uint8_t pack_info;
    uint8_t addr_len;
    datasize_t ret;
    datasize_t received_size;
    uint16_t size, sentsize;
    uint8_t* mode_msg;
    uint16_t any_port = 50000;

    if(loopback_mode == AS_IPV4)
    {
            mode_msg = "IPv4 mode";
    }else if(loopback_mode == AS_IPV6)
    {
            mode_msg = "IPv6 mode";
    }else
    {
            mode_msg = "Dual IP mode";
    }

    getsockopt(sn, SO_STATUS, &status);
    switch (status)
    {
    case SOCK_UDP:
        getsockopt(sn, SO_RECVBUF, &received_size);
        if(received_size > DATA_BUF_SIZE) received_size = DATA_BUF_SIZE;
        if(received_size>0)
        {
            ret = recvfrom(sn, buf, received_size, (uint8_t*)&dest_ip, (uint16_t*)&dest_port, &addr_len);
            buf[ret]=0x00;
            printf("recv from [%d.%d.%d.%d][%d]: %s\n",dest_ip[0],dest_ip[1],dest_ip[2],dest_ip[3],dest_port,buf);
            if(ret <= 0)
             return ret;
            received_size = (uint16_t) ret;
            sentsize = 0;
            while(sentsize != received_size){
                ret = sendto(sn, buf+sentsize, received_size-sentsize, dest_ip, dest_port, addr_len);

                if(ret < 0) return ret;

                sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
             }
        }
        break;
    case SOCK_CLOSED:
        setSn_DHAR(sn, multicast_mac);
        setSn_DIP4R(sn, multicast_ip);
        setSn_DPORTR(sn, multicast_port);
        switch(loopback_mode)
        {
        case AS_IPV4:
           socket(sn,Sn_MR_UDP4, any_port, SF_MULTI_ENABLE);
           break;
        case AS_IPV6:
           socket(sn,Sn_MR_UDP6, any_port, SF_MULTI_ENABLE);
           break;
        case AS_IPDUAL:
            socket(sn,Sn_MR_UDPD, any_port, SF_MULTI_ENABLE);
            break;
        }
        printf("%d:UDP Multicast looptest as %s\r\n",sn,mode_msg);
        printf("%d:UDP Multicast IP: %d.%d.%d.%d\r\n",sn,multicast_ip[0],multicast_ip[1],multicast_ip[2],multicast_ip[3]);
        printf("%d:UDP Multicast PORT: %d\r\n",sn,multicast_port);
        break;
    default:
        break;
    }
}


